<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\model\User\Pay as PayModel;
use app\common\model\User\Record as RecordModel;
use app\common\model\User\User as UserModel;
use app\common\validate\User\Record as RecordValidate;
use Exception;
use think\exception\ValidateException;
use think\facade\Db;

class Pay extends BaseController
{
    protected $middleware = [
        \app\admin\middleware\LoginAuth::class
    ];
    // 充值记录列表
    public function index()
    {
        $menu = [
            'name' => '用户管理',
            'title' => '充值记录'
        ];
        $searchfield = $this->request->param('search_field', 'user.nickname');
        $keyword = $this->request->param('keyword');
        $where = [];
        if ($searchfield && $keyword) {
            $where[] = [$searchfield, 'like', "%$keyword%"];
        }
        // 每页显示数量
        $num = 10;
        $PayList = PayModel::hasWhere('user', [['deletetime', 'EXP', Db::raw('IS NULL')]])->hasWhere('admin', [], '*', 'LEFT')->where($where)->order('createtime', 'desc')->paginate(['list_rows' => $num, 'query' => request()->param()]);
        // 当前页
        $page = $PayList->currentPage();
        return view('', [
            'menu' => $menu,
            'searchfield' => $searchfield,
            'keyword' => $keyword,
            'PayList' => $PayList,
            'num' => $num,
            'page' => $page
        ]);
    }
    // 充值记录删除
    public function del()
    {
        $payid = $this->request->param('payid');
        $ids = $this->request->param('ids');
        $action = $this->request->param('action');
        if ($action == 'Del') {
            $Pay = PayModel::find($payid);
            if (!$Pay) {
                $this->error('充值记录不存在');
            }
            $result = PayModel::destroy($payid);
            if ($result === false) {
                $this->error('充值记录删除失败');
            }
            $this->success('充值记录删除成功');
        }
        if ($action == 'BatchDelete') {
            $PayList = PayModel::whereIn('id', $ids)->select();
            foreach ($PayList as $key => $item) {
                if ($item['status'] == 0) {
                    $this->error("未审核的记录无法删除,请重新选择");
                }
            }
            $result = PayModel::destroy(['id' => $ids]);
            if ($result === false) {
                $this->error('充值记录删除失败');
            }
            $this->success('充值记录删除成功');
        }
    }
    public function status()
    {
        $payid = $this->request->param('payid');
        $ids = $this->request->param('ids');
        $action = $this->request->param('action');
        // 通过中间件将登录用户数据赋值
        $LoginAdmin = $this->request->LoginAdmin;
        // 单条审核通过
        if ($action == 'adopt') {
            $Pay = PayModel::find($payid);
            if (!$Pay) {
                $this->error('充值记录不存在');
            }
            $User = UserModel::find($Pay['userid']);
            if (!$Pay) {
                $this->error('用户不存在');
            }
            // 开启事务
            PayModel::startTrans();
            UserModel::startTrans();
            RecordModel::startTrans();
            // 将审核状态改为1
            $Pay->status = 1;
            $Pay->adminid = $LoginAdmin['id'];
            // 执行更新语句
            $PayStatus = $Pay->save();
            if ($PayStatus === false) {
                $this->error('更新审核状态失败');
            }
            $point = bcadd((string)$User['point'], (string)$Pay['point']);
            $User->point = $point;
            $UserStatus = $User->save();
            if ($UserStatus === false) {
                PayModel::rollback();
                $this->error('用户积分更新失败');
            }
            $data = [
                'content' => "您的充值审核已通过，{$Pay['point']}积分已到账",
                'userid' => $User['id'],
                'point' => $Pay['point'],
                'state' => 3
            ];
            try {
                validate(RecordValidate::class)->check($data);
            } catch (ValidateException $e) {
                PayModel::rollback();
                UserModel::rollback();
                $this->error($e->getMessage());
            }
            $RecordStatus = RecordModel::create($data);
            if ($RecordStatus === false) {
                PayModel::rollback();
                UserModel::rollback();
                $this->error('新增消费记录失败');
            }
            if ($UserStatus === false || $PayStatus === false || $RecordStatus === false) {
                PayModel::rollback();
                UserModel::rollback();
                RecordModel::rollback();
                $this->error('审核通过失败');
            } else {
                PayModel::commit();
                UserModel::commit();
                RecordModel::commit();
                $this->success('审核通过成功');
            }
        }
        // 批量审核通过
        if ($action == 'adopts') {
            try {
                $PayList = PayModel::whereIn('id', $ids)->select();
                foreach ($PayList as $key => $item) {
                    if ($item['status'] != 0) {
                        throw new Exception("存在已审核的记录,请重新选择");
                    }
                }
                // 开启事务
                PayModel::startTrans();
                UserModel::startTrans();
                RecordModel::startTrans();
                // 更新充值状态
                $PayData = [];
                // 新增消费记录
                $RecordData = [];
                foreach ($PayList as $key => $item) {
                    $PayData[] = [
                        'id' => $item['id'],
                        'status' => 1,
                        'adminid' => $LoginAdmin['id']
                    ];
                    $user = UserModel::find($item['userid']);
                    $point = bcadd((string)$user['point'], (string)$item['point']);
                    $user->point = $point;
                    $UserStatus = $user->save();
                    if ($UserStatus === FALSE) {
                        throw new Exception('更新用户积分失败');
                    }
                    $RecordData[] = [
                        'content' => "您的充值审核已通过，{$item['point']}积分已到账",
                        'userid' => $item['userid'],
                        'point' => $item['point'],
                        'state' => 3
                    ];
                }
                // 批量更新充值状态
                $PayModel = new PayModel();
                $PayStatus = $PayModel->saveAll($PayData);
                if ($PayStatus === FALSE) {
                    throw new Exception('更新审核状态失败');
                }
                // 新增消费记录
                foreach ($RecordData as $key => $item) {
                    validate(RecordValidate::class)->check($item);
                    $RecordStatus = RecordModel::create($item);
                    if ($RecordStatus === FALSE) {
                        throw new Exception('新增消费记录失败');
                    }
                }
            } catch (ValidateException $e) {
                PayModel::rollback();
                UserModel::rollback();
                RecordModel::rollback();
                $this->error($e->getError());
            } catch (Exception $error) {
                PayModel::rollback();
                UserModel::rollback();
                RecordModel::rollback();
                $this->error($error->getMessage());
            }
            PayModel::commit();
            UserModel::commit();
            RecordModel::commit();
            $this->success('批量审核通过成功');
        }
        // 单条审核不通过
        if ($action == 'fail') {
            $Pay = PayModel::find($payid);
            if (!$Pay) {
                $this->error('充值记录不存在');
            }
            $User = UserModel::find($Pay['userid']);
            if (!$Pay) {
                $this->error('用户不存在');
            }
            // 将审核状态改为2
            $Pay->status = 2;
            $Pay->adminid = $LoginAdmin['id'];
            // 执行更新语句
            $PayStatus = $Pay->save();
            if ($PayStatus === false) {
                $this->error('审核不通过成功失败');
            }
            $this->success('审核不通过成功');
        }
        // 批量审核不通过
        if ($action == 'fails') {
            $PayList = PayModel::whereIn('id', $ids)->select();
            foreach ($PayList as $key => $item) {
                if ($item['status'] != 0) {
                    $this->error("存在已审核的记录,请重新选择");
                }
            }
            // 更新商品库存
            $PayData = [];
            foreach ($PayList as $key => $item) {
                $PayData[] = [
                    'id' => $item['id'],
                    'status' => 2,
                    'adminid' => $LoginAdmin['id']
                ];
            }
            // halt($PayData);
            $PayModel = new PayModel();
            // 批量更新
            $PayStatus = $PayModel->saveAll($PayData);
            if ($PayStatus === FALSE) {
                $this->error('批量审核不通过失败');
            }
            $this->success('批量审核不通过成功');
        }
    }
}
